<?php
require "./common/function.php";
require "./config/dbconfig.php";
require "./config/common.php";

$a = $_REQUEST['a'];
if($a=='logout'){
//    清除cookie
    setcookie("username",'',time()-1);
    setcookie("roleId",'',time()-1);
    setcookie("isLogin",'false',time()-1);
    require "./html/login.html";
    exit;
}

//判断用户是否处于登录状态
if(isset($_COOKIE['username']) && $_COOKIE['isLogin']=='true' && isset($_COOKIE['roleId']) ){
    $roleId = $_COOKIE['roleId'];
    $name = $_COOKIE['username'];

    display($roleId);

}
//进行用户登录
if($_POST){
    //    获取用户登录信息
    $name=$_REQUEST["username"];
    $pwd = $_REQUEST["pwd"];
    $roleId=$_REQUEST['role'];

//    判空
    if (empty($name)){
        $errMsg = [false,'用户名不能为空'];
        require "html/login.html";
        exit;
    }
    if (empty($pwd)){
        $errMsg = [false,'密码不能为空'];
        require "html/login.html";
        exit;
    }
    if (empty($roleId)){
        $errMsg = [false,"角色不能为空"];
        require "html/login.html";
        exit;
    }
    $pwd2=strtoupper(md5($pwd));

    $sql = "select * from t_user where username='$name' and `password`='$pwd2' and role_id='$roleId' ";
    $result = getMySql($sql,'查询失败');
    if($result){
       if(mysqli_num_rows($result)){
           //获取一条用户信息
           $user = mysqli_fetch_array($result);
           //存储用户信息，有效期一小时
           setcookie("username",$user['username'],time()+3600);
           setcookie("roleId",$user['role_id'],time()+3600);
           setcookie("isLogin",'true',time()+3600);
           setcookie("uId",$user['uid'],time()+3600);

//           TODO 登录判断是管理员还是用户
           display($roleId);
       } else{
           $errMsg = [false,"用户不存在"];
           require "./html/login.html";
           exit;
       }
    }
}

//跳转到html页面
require "./html/login.html";
exit;

function display($roleId){

    if($roleId=="1"){
        $proUrl = productUrl;
        $ordUrl = orderUrl;
        $editPwd = editPwdUrl;
        //管理员
        require "./html/index.html";
    }else{
        $sql="select a.*,b.category flname from t_product a left join t_category b on a.category=b.id where a.status=0";
        $result = getMySql($sql,"查询热门商品信息失败");
        if($result){
            if(mysqli_num_rows($result)){
                $products = mysqli_fetch_all($result,MYSQLI_ASSOC);
            }
        }
        //用户
        require "./q_user/html/index.html";
    }
    exit;
}